package org.java.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 实验框架的核心组件。监听Spring上下文刷新事件，并自动执行所有注册的实验。
 */
@Component
public class SimpleTestRunner implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger logger = LoggerFactory.getLogger(SimpleTestRunner.class);

    @Value("${experiments.enabled:true}")
    private boolean experimentsEnabled;

    private ApplicationContext applicationContext;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (!experimentsEnabled) {
            logger.info("Experiments are disabled. Skipping execution.");
            return;
        }

        logger.info("Spring Context Refreshed. Starting experiments...");
        // 获取ApplicationContext
        this.applicationContext = event.getApplicationContext();

        // 查找所有实现了ISimpleTest接口的Bean
        Map<String, ISimpleTest> experimentBeans = applicationContext.getBeansOfType(ISimpleTest.class);

        if (experimentBeans.isEmpty()) {
            logger.warn("No experiments found to run.");
            return;
        }

        logger.info("Found {} experiment(s) to run.", experimentBeans.size());

        // 逐个执行实验
        for (Map.Entry<String, ISimpleTest> entry : experimentBeans.entrySet()) {
            String beanName = entry.getKey();
            ISimpleTest experiment = entry.getValue();
            try {
                logger.info("Executing experiment: [{}]", beanName);
                experiment.execute();
                logger.info("Experiment [{}] completed successfully.", beanName);
            } catch (Exception e) {
                logger.error("Experiment [{}] failed with exception: {}", beanName, e.getMessage(), e);
                // 可以选择继续执行下一个实验，或者中断
            }
        }

        logger.info("All experiments have been executed.");
    }
}